package com.agrm.rabc.controller;


import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.rabc.dto.UserGroupMapping;
import com.agrm.rabc.service.UserGroupMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api/v1/user_groups", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserGroupMappingApi {
    private UserGroupMappingService userGroupMappingService;

    @Autowired
    public void setUserGroupMappingService(UserGroupMappingService userGroupMappingService) {
        this.userGroupMappingService = userGroupMappingService;
    }

    @GetMapping
    public ResponseResult findAll(UserGroupMapping ugm) {
        List<UserGroupMapping> mappings = userGroupMappingService.findAll(ugm);
        return ResponseResult.okResult(mappings);
    }

    @GetMapping("/id/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id) {
        UserGroupMapping ugm = userGroupMappingService.findById(id);
        if (ugm == null) {
            return ResponseResult.errorResult(-1,"保存用户-组关联失败");
        } else {
            return ResponseResult.okResult(ugm);
        }
    }

    @PostMapping
    public ResponseResult save(@RequestBody UserGroupMapping ugm) {
        boolean success = userGroupMappingService.save(ugm);
        if (success) {
            return ResponseResult.okResult(200,"");
        } else {
            return ResponseResult.errorResult(-1,"保存用户-组关联失败");
        }
    }

    @PutMapping
    public ResponseResult update(@RequestBody UserGroupMapping ugm) {
        boolean success = userGroupMappingService.update(ugm);
        if (success) {
            return ResponseResult.okResult(200,"");
        } else {
            return ResponseResult.errorResult(-1,"修改用户-组关联失败");
        }
    }

    @DeleteMapping
    public ResponseResult deleteByIds(@RequestBody Integer[] ids) {
        int count = userGroupMappingService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseResult.okResult(count);
        } else {
            return ResponseResult.errorResult(-1,"删除用户-组关联失败");
        }
    }
}
